/**
 * Created by chengming on 18/5/24.
 * version 1.0
 */
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const request = require('request-promise');
const vm = require('vm');
const cheerio = require('cheerio');
const urlTool = require('url');
const logger = require('../../conf/logger');

/**
 * 中华粮网
 * @type {module.Cngrain}
 */
module.exports = class Cngrain extends ArticleHrefAdapter{

	initWinEnv(){
		global.window = {
			location:"http://www.cngrain.com/Info/KindInfoList/4_1207959552_0_2_4",
			innerWidth:1232,
			innerHeight:632,
			screenX:11,
			screenY:22,
			screen:{
				width:1280,
				height:800
			}
		};

		global.document = {
			location:{
				href:''
			},
			documentElement:{
				clientWidth:1217,
				clientHeight:550
			},
			body:{
				clientWidth:1217,
				clientHeight:1467
			},
			_cookie: [],

			get cookie(){
				return this._cookie;
			},

			set cookie(val){
				this._cookie.push(val);
			},

		};


		global.cookie={

		};

	}

	async doRequest(){

		//初始化窗口属性
		this.initWinEnv();

		//创建全局cookie
		var jar = request.jar();
		
		//使用cookie
		const jsbody = await request({
			jar:jar,
			url: this.requestUrl,
			headers:{
				'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
			}
		});

		let $ = cheerio.load(jsbody);
		let realLink = $('script').html();
		// realLink = ''
        window.location=this.requestUrl;
        document.location.href=this.requestUrl;
        vm.runInThisContext(realLink+" t3_ar_guard();");
		let newUrl = urlTool.resolve(this.requestUrl, window.location);

		for(let cookieStr of document.cookie){
			let cookie = request.cookie(cookieStr);
			jar.setCookie(cookie, this.requestUrl);
		}

		return await request({
			jar:jar,
			url:newUrl,
			headers:{
				'Referer':this.requestUrl,
				'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
			},
			encoding:null
		});
	}
}